
$(function(){
	//操作Cookie
	function _getCookie(key) {
	    var result = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)"));
	    return result != null ? decodeURIComponent(result[2]) : null;
	}

	function _setCookie(key, value, expireDay) {
	    if (expireDay) {
	        var date = new Date();
	        date.setTime(date.getTime() + expireDay *24* 3600 * 1000);
	        document.cookie = key + "=" + encodeURIComponent(value) + ";path=/;expires=" + date.toGMTString();
	    } else {
	        document.cookie = key + "=" + encodeURIComponent(value) + ";path=/";
	    }
	}
	
	
/*
var carCityData = {
		310100:{"code":"310100","name":"上海市","spuIdList":["3057","3058","3063"]},
		320500:{"code":"320500","name":"苏州市","spuIdList":["3057","3058","3063"]},
		510100:{"code":"510100","name":"成都市","spuIdList":["3057","3058","3063"]},
		330200:{"code":"330200","name":"宁波市","spuIdList":["3057","3058","3063"]},
		330100:{"code":"330100","name":"杭州市","spuIdList":["3057","3058","3063"]},
		410100:{"code":"410100","name":"郑州市","spuIdList":["3057","3058","3063"]},
		370100:{"code":"370100","name":"济南市","spuIdList":["3057","3058","3063"]},
		420100:{"code":"420100","name":"武汉市","spuIdList":["3057","3058","3063"]}
				};



function cityCookie(cityId, cityName){
	_setCookie("city.id",cityId,365);
	_setCookie("city.name",cityName,365);
}

//显示选择城市
function cityShow(){
	$(".pop-mask").css("height",document.body.scrollHeight);
	$(".pop-mask").show();
	$(".city-box").css("top",$(document).scrollTop()+($(window).height()-$(".city-box").height())/2);
	$(".city-box").show();
};

$(".city-body").find("a").on("click",function(){
	var cityId= ($(this).attr('cityid'));
	var cityName=($(this).attr('name'));
	cityCookie(cityId, cityName);
	window.location.reload(true);
	$(".pop-mask").hide();
	$(".city-box").hide();
});

//根据城市Cookie 设置本期车型不同链接
var MALL_CITY_ID = _getCookie("city.id"),
	liEle = $('.car-modle-item','.car-modle-row'),
	eleLen = liEle.length;

if(MALL_CITY_ID != null){
	for(var ci = 0;ci<eleLen;ci++){
		liEle.eq(ci).find('.join-btn').attr('href','http://car.chexiang.com/product/'+carCityData[MALL_CITY_ID]['spuIdList'][ci]+'.htm');
	}
} else {
	for(var ci = 0;ci<eleLen;ci++){
		liEle.find('.join-btn').attr('href','javascript:void(0)');
	}
	cityShow();
}
*/





//给所有的图片和按钮绑定 快速登录注册函数；
$(".bindCheckLogin").on("click",function(){
	var btnType = $(this).attr('btnType');
	window._clickThisBtn=$(this);
	switch (btnType) {
		case 'current':
			//先存下来当前按钮在这一组中的位置，以供获取当前标签所加的自定义属性；
			window.carType.current = $(".bindCheckLogin",".car-modle-row").index(this);
			//这里使backCallName变量为获取的标签类型，以便执行相应的函数
			window.backCallName = 'current';
			break;
		case 'forcast':
			window.carType.forcast = $(".bindCheckLogin",".forecast-model").index(this);
			window.backCallName = 'forcast';
			break;
		case 'vote':
			window.carType.vote = $(".bindCheckLogin",".half-price-box").index(this);
			window.backCallName = 'vote';
			break;
		case 'halfPrice':
			if(!parseInt($(".car-model").val())){
				turnActive();
				return false;
			}
			window.backCallName = 'halfPrice';
			break;
	};
	checkLogin(accountQuickBase,'B');
});	


//侧边栏部分 
$(".tit i").click(function(){
	$(this).parents('.js-weixin').addClass("weixin-show").siblings('li').removeClass('weixin-show');
});
$(".js-weixin .close").click(function(){
	$(this).parents('.js-weixin').removeClass('weixin-show');
});

$(".backtoTop").click(function(){
	$("html,body").animate({"scrollTop":0},600);
});
//添加客服
$('.mainsite-im').click(function(){
	var service ='http://kf1.chexiang.com/new/client.php?arg=admin&style=7&referer='+document.location.href+'&keyword=&charset=utf-8';
	$.ajax({
		url:'/ImMember/getUserInfo.htm',
		type:'post',
		dataType:'json',
		success:function(data){
			if(data==""){
				window.open(service, "车享客服", "height=573, width=803, top=80, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=n o, status=no");
			}else{
				var kfUrl=service+"&userinfo="+data;
				window.open(kfUrl, "车享客服", "height=573, width=803, top=80, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=n o, status=no");
			}
		},
		error:function(errorMessage){
			window.open(service, "车享客服", "height=573, width=803, top=80, left=300,toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=n o, status=no");
		}
	});
});
//下拉选择
$.ajax({
	url:"/commonAjax/getMultiMenu.htm",
	type: "GET",
	dataType: "json",
	success: function(data){
		var e_data= eval("("+data+")");
		ECar.seriesSelect($("#vote-sel"), {
			  data: e_data,
			  selects: ["car-brand", "car-series" ,"car-model"],
			  nodata: null
		});
	}
});

//校验select
function verify(a,b){
	if(a[0].value==""||a[0].value==0){
		$(".warning-tips").text(b);
		$(".warning-tips").show();
		a.parent().addClass("sel-bor-warn");
	}else{
		$(".warning-tips").hide();
		a.parent().removeClass("sel-bor-warn");
	}
};
var oCarBrand=$(".car-brand");
var oCarSeries=$(".car-series");
var oCarModel=$(".car-model");

oCarBrand.on("change",function(){
	verify(oCarBrand,"请选择品牌");	
});
oCarSeries.on("change",function(){
	verify(oCarSeries,"请选择车系");	
})
oCarModel.on("change",function(){
	verify(oCarModel,"请选择车型");
});
//按钮满足条件才可投票否则提示
function turnActive(){
	if(parseInt(oCarBrand.val())&&parseInt(oCarSeries.val())&&parseInt(oCarModel.val())){
		$(".warning-tips").hide();
	}else{
		$(".warning-tips").text("请选择你所要的特价车（品牌、车型、车系）");
		$(".warning-tips").show();
	}
}
//第一次判断是否登录，如未登录，则刷新页面
function isLogin(){
	if(!logoinFlag){
		window.location.reload();
	}
}
var activityCode="第七期特殊车20151028";
//提交预告车型
window.forcastFun=function(){
	//location.reload();
	var param={};
	param['activityCode']  = activityCode;
	param['velBrandName']  = encodeURIComponent($(".bindCheckLogin",".forecast-model").eq(window.carType.forcast).attr('brandName'));
	param['velSeriesName']  = encodeURIComponent($(".bindCheckLogin",".forecast-model").eq(window.carType.forcast).attr('seriesName'));
	param['velModelName']  = encodeURIComponent($(".bindCheckLogin",".forecast-model").eq(window.carType.forcast).attr('modelName'));
	param['velModelId']  = $(".bindCheckLogin",".forecast-model").eq(window.carType.forcast).attr('modelId');
	param['cityId']  = _getCookie("city.id");
	param['activityNo'] = $(".bindCheckLogin",".forecast-model").eq(window.carType.forcast).attr('activeNumber');
	$.ajax({
		url:"/promotion/saveLiuzi.htm",
		type: "POST",
		data: param,
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		success: function(data){
			if(data>0)
			{	
				//投票后按钮置灰
				_clickThisBtn.attr("class","order-btn-grey");
				_clickThisBtn.text("已预约");
				_clickThisBtn.off("click");
				ECar.easyDialog.open({
					container : {
						header : '提示',
						content : '<div style="text-align:center">预约成功！</div>'						
					},
					callback:isLogin
				});
			} else {
					//投票后按钮置灰
					_clickThisBtn.attr("class","order-btn-grey");
					_clickThisBtn.text("已预约");
					_clickThisBtn.off("click");
					ECar.easyDialog.open({
						container : {
							header : '提示',
							content : '<div style="text-align:center">您已经预约，不能重复操作！</div>'
						},
						callback:isLogin
					});
			}
			
		},
		error: function(){
			ECar.easyDialog.open({
				container : {
					header : '提示',
					content : '<div style="text-align:center">未提交成功，请稍后再试</div>'
				}
			});
		}
	});
}
//提交投票车型
window.voteFun=function(){
	var param={};
	param['activityCode']  = activityCode;
	param['velBrandName']  = encodeURIComponent($(".bindCheckLogin",".half-price-box").eq(window.carType.vote).attr('brandName'));
	param['velSeriesName']  = encodeURIComponent($(".bindCheckLogin",".half-price-box").eq(window.carType.vote).attr('seriesName'));
	param['velSeriesId']  = $(".bindCheckLogin",".half-price-box").eq(window.carType.vote).attr('seriesId');
	param['cityId']  = _getCookie("city.id");
	param['activityNo'] = $(".bindCheckLogin",".half-price-box").eq(window.carType.vote).attr('activeNumber');
	$.ajax({
		url:"/promotion/saveLiuzi.htm",
		type: "POST",
		data: param,
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		success: function(data){
			if(data>0)
			{	//点击后人数增加
				var oZhiChi=parseInt(_clickThisBtn.next().text())+1;
				_clickThisBtn.next().text(oZhiChi+"人支持");
				//投票后按钮置灰
				_clickThisBtn.attr("class","vote-btn-grey");
				_clickThisBtn.text("已投票");
				_clickThisBtn.off("click");
				ECar.easyDialog.open({
					container : {
						header : '提示',
						content : '<div style="text-align:center">投票成功</div>'
					},
					callback:isLogin
				});
			}else
				{
				//投票后按钮置灰
				_clickThisBtn.attr("class","vote-btn-grey");
				_clickThisBtn.text("已投票");
				_clickThisBtn.off("click");
					ECar.easyDialog.open({
						container : {
							header : '提示',
							content : '<div style="text-align:center">您已经参加过投票，不能重复操作！</div>'
						},
						callback:isLogin
					});
				}
			
		},
		error: function(){
			ECar.easyDialog.open({
				container : {
					header : '提示',
					content : '<div style="text-align:center">未提交成功，请稍后再试</div>'
				}
			});
		}
	});
}

//发起半价车
window.goHalfPrice = function (){
	//event.stopPropagation();
	if(parseInt($(".car-model").val())){
		//提交数据
		var velSeriesName = $(".car-series option").not(function(){ return !this.selected }).text();
		var velModelName = $(".car-model option").not(function(){ return !this.selected }).text();
		var modelName=velSeriesName+'-'+velModelName;
		var param={};
		param['activityCode']  = activityCode;
		param['velModelName']  = velModelName;
		param['velSeriesName']  = velSeriesName;
		param['velSeriesId']  = $(".car-series option").not(function(){ return !this.selected }).val();
		param['velModelId']  = $(".car-model option").not(function(){ return !this.selected }).val();
		param['velBrandId']  = $(".car-brand  option").not(function(){ return !this.selected }).val();
		param['velBrandName']  = $(".car-brand  option").not(function(){ return !this.selected }).text();
		param['cityId']  = _getCookie("city.id");
		param['activityNo'] = $(".bindCheckLogin",".sel-grey").attr("activeNumber");
		$.ajax({
			url:"/promotion/saveLiuzi.htm",
			type: "POST",
			data: param,
			dataType: "json",
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			success: function(data){
				if(data>0)
				{	
					ECar.easyDialog.open({
						container : {
							header : '提示',
							content : '<div style="text-align:center">发起成功，谢谢参与！</div>'
						},
						callback:isLogin
					});
				}else
					{
						ECar.easyDialog.open({
							container : {
								header : '提示',
								content : '<div style="text-align:center">本期你已发起过特价车，下期再来吧</div>'
							},
							callback:isLogin
						});
					}
				
			},
			error: function(){
				ECar.easyDialog.open({
					container : {
						header : '提示',
						content : '<div style="text-align:center">未提交成功，请稍后再试</div>'
					}
				});
			}
		});
	}else{
		turnActive();
		return false;
	}
}

//活动规则，弹框函数
function popRule(){
	$(".pop-mask").css("height",document.body.scrollHeight);
	$(".pop-mask").show();
	$(".pop-rule").css("top",$(document).scrollTop()+($(window).height()-$(".pop-rule").height())/2);
	$(".pop-rule").show();
}
//点击4个链接即可弹出对话框
$(".activity-rule").on("click",function(){
	popRule();
});
//关闭活动规则，弹框
$(".pop-colse-btn").on("click",function(){
	$(".pop-mask").hide();
	$(".pop-rule").hide();
})
//添加兼容IE8/9 select
/*var browser=navigator.appName ;
var b_version=navigator.appVersion.split(";"); 
var trim_Version=b_version[1].replace(/[ ]/g,"");
if((browser=="Microsoft Internet Explorer" && trim_Version=="MSIE8.0")||(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE9.0")) 
{ 
    $(".sel-bor").removeClass("sel_parent_height");
    $(".sel-bor select").removeClass("sel_height");
}
*/
})/*整个window.onload结束*/

window.carType = {
	current :'',
	forcast:'',
	vote:''
};
window.backCallName = '';
/*快速注册登录成功后的回调函数*/

window.backCallFun = function(obj){
	
	//注册登录成功后的后续操作
	switch (backCallName) {
		case 'current':
			currentFun();
			break;
		case 'forcast':
			forcastFun();
			break;
		case 'vote':
			voteFun();
			break;
		case 'halfPrice':
			goHalfPrice();
			break;
	};
	
};
//往期回顾功能修改
$('#passed-event').cxScroll({
  direction: 'bottom',
  time:"2000"
});

ECar.pin({            
    'obj':$('#passed-event')//必须
    
  });
//提交本期车型
/*window.currentFun=function(){
	var param={};
	param['velSeriesName']  =encodeURIComponent( $(".bindCheckLogin",".car-modle-row").eq(window.carType.current).parent().find(".modelName").text());
	param['velSeriesId']  = $(".bindCheckLogin",".car-modle-row").eq(window.carType.current).attr('seriesId');
	param['cityId']  = _getCookie("PROMOTION_CITY_ID");
	param['activityNo'] = $(".bindCheckLogin",".car-modle-row").eq(window.carType.current).attr('activeNumber');
	$.ajax({
		url:"/promotion/saveLiuzi.htm",
		type: "POST",
		data: param,
		dataType: "json",
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		success: function(data){
			if(data>0)
			{	//按钮置灰
				_clickThisBtn.attr("class","join-btn-grey");
				_clickThisBtn.text("已抢定");
				//参与数、 人气数刷新
				var oCanYu=parseInt( _clickThisBtn.parent().find(".join").text().split("：")[1] )+1;
				var oRenQi=parseInt( _clickThisBtn.parent().find(".popularity").text().split("：")[1])+oCanYu*5;
				_clickThisBtn.parent().find(".counter").html(' <span class="popularity">人气：'+oRenQi+'</span>\
			            <span class="join">参与：'+oCanYu+'</span>');
				ECar.easyDialog.open({
					container : {
						header : '提示',
						content : '<div style="text-align:center">抢定成功！</div>'
					}
				});
			}else
				{
					ECar.easyDialog.open({
						container : {
							header : '提示',
							content : '<div style="text-align:center">您已经抢定成功，不能重复操作！</div>'
						}
					});
				}
			
		},
		error: function(){
			ECar.easyDialog.open({
				container : {
					header : '提示',
					content : '<div style="text-align:center">未提交成功，请稍后再试</div>'
				}
			});
		}
	});
}*/
